const fs = require("fs");
const path = require("path");
const uuid = require("uuid");

/**
 * @description: 处理post请求是的参数，通过给ctx.request.body赋值
 * @param {*}
 * @return {*}
 */
function bodyparser() {
  return async (ctx, next) => {
    await new Promise((resolve, reject) => {
      let arr = [];
      ctx.req.on("data", function (data) {
        arr.push(data);
      });
      ctx.req.on("end", () => {
        let type = ctx.get("Content-Type");
        // console.log(type);
        if (type.includes("multipart/form-data")) {
          let boundary = "--" + type.split("=")[1];
          //   console.log(boundary);
          let buffer = Buffer.concat(arr);
          let lines = buffer.split(boundary).slice(1, -1);
          let obj = Object.create(null);
          lines.forEach((line) => {
            console.log(line.toString());
            let [head, content] = line.split("\r\n\r\n");
            head = head.toString();
            let key = head.match(/name="(.+?)"/)[1];
            // console.log(head);
            // 解析不同类型，文件以及数据
            if (head.includes("filename")) {
              // 上传的是文件类型
              let filename = uuid.v4();
              fs.writeFileSync(
                path.resolve(__dirname, "upload", filename),
                content.slice(0, -2),
                "utf8"
              );
              obj[key] = filename;
            } else {
              obj[key] = content.slice(0, -2).toString();
            }
          });
          ctx.request.body = obj;
          resolve();
        } else {
          resolve();
        }
      });
    });
    await next();
  };
}
Buffer.prototype.split = function (dep) {
  let len = Buffer.from(dep).length;
  let offset = 0;
  let result = [];
  let current;
  // 把找到的位置索引赋值给current
  while ((current = this.indexOf(dep, offset)) !== -1) {
    result.push(this.slice(offset, current)); //每次截取的数据添加到数组
    offset = current + len; // 增加查找偏移量
  }
  result.push(this.slice(offset));
  return result;
};
module.exports = bodyparser;
